/** Description of SmallWidgetProvider.java 
 * @version 1.0
 * 
 * @author panther
 * Jayant Pratim Saikia
 * jay.saikia@gmail.com
 *
 */
package com.panther.awp.android.smoker.widgets;

import java.util.Currency;
import java.util.Locale;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.preference.PreferenceManager;
import android.view.Gravity;
import android.widget.Toast;

import com.panther.awp.android.smoker.R;
import com.panther.awp.android.smoker.activities.animate.AnimateScreen;
import com.panther.awp.android.smoker.async.SmokeNowThread;
import com.panther.awp.android.smoker.async.SmokeTimerTask;
import com.panther.awp.android.smoker.async.WidgetUpdateTask;
import com.panther.awp.android.smoker.cache.Cache;
import com.panther.awp.android.smoker.database.AbstractDbAdapter;
import com.panther.awp.android.smoker.database.MyDBWrapper;
import com.panther.awp.android.smoker.helpers.GeneralHelper;

public class SmallWidgetProvider extends AppWidgetProvider {
	
	private SmokeTimerTask smokeTimerTask;
	private WidgetUpdateTask widgetUpdateTask;
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		if(smokeTimerTask != null) {
			smokeTimerTask.cancel(true);
		}
		if(widgetUpdateTask != null) {
			widgetUpdateTask.cancel(true);
		}
		super.onDeleted(context, appWidgetIds);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		
		if(intent.getAction().equalsIgnoreCase(GeneralHelper.SMALL_SMOKE_WIDGET_RECEIVER)) {
			if(intent.getExtras() != null) {
				String brandIdStr = intent.getExtras().getString(GeneralHelper.BRAND_ID);
				String brandName = intent.getExtras().getString(GeneralHelper.BRAND_NAME);
				String brandCost = intent.getExtras().getString(GeneralHelper.BRAND_PRICE);
				try {
					Long brandId = Long.parseLong(brandIdStr);
					
					SmokeNowThread thread = new SmokeNowThread(context, brandId);
					thread.start();
					
					SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
			        String currencyCode = prefs.getString("yCurrency", Currency.getInstance(Locale.getDefault()).getCurrencyCode());
					
					final NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
					final Notification notification = new Notification(R.drawable.icon, "Smoking " + brandName, System.currentTimeMillis());
					notification.flags |= Notification.FLAG_AUTO_CANCEL;
					Intent notificationIntent = new Intent();
					PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
					notification.setLatestEventInfo(context, "Smoked " + brandName, "It cost you " + Currency.getInstance(currencyCode).getSymbol(Locale.getDefault()) + " " + brandCost + ".", pendingIntent);
					notificationManager.notify(666, notification);

					smokeTimerTask = new SmokeTimerTask(context);
					smokeTimerTask.execute();
					
					Intent animationIntent = new Intent(context, AnimateScreen.class);
					animationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					animationIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
					animationIntent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
					context.startActivity(animationIntent);
			        
				} catch (NumberFormatException e) {
					Toast toast = Toast.makeText(context, "Please select brand to smoke ...", Toast.LENGTH_SHORT);
					toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 20);
					toast.show();
				}
			}
		} else if(intent.getAction().equalsIgnoreCase(GeneralHelper.SMALL_WIDGET_SCROLLDOWN_RECEIVER)) {
			if(intent.getExtras() != null) {
				String brandIdStr = intent.getExtras().getString(GeneralHelper.BRAND_ID);
				try {
					Long id = Long.parseLong(brandIdStr);
					Cursor cursor = MyDBWrapper.getInstance(context.getApplicationContext()).getmBTDbHelper().fetchBeforeThisBrand(id);
					cursor.moveToFirst();
					while(!cursor.isAfterLast()) {
						String brandUri = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
						GeneralHelper.updateRemoteView(context, cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_PK_ID)), cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND)), cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE)), Cache.getCacheFile(brandUri));
						cursor.moveToNext();
					}
					cursor.close();
				} catch (NumberFormatException e) {
					Cursor cursor = MyDBWrapper.getInstance(context.getApplicationContext()).getmBTDbHelper().fetchMostSmokedBrand();
					cursor.moveToFirst();
					while(!cursor.isAfterLast()) {
						String brandUri = cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_IMAGE_URI));
						GeneralHelper.updateRemoteView(context, cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_PK_ID)), cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND)), cursor.getString(cursor.getColumnIndexOrThrow(AbstractDbAdapter.BT_BRAND_PRICE)), Cache.getCacheFile(brandUri));
						cursor.moveToNext();
					}
					cursor.close();
				}
			}
		}
		
		super.onReceive(context, intent);
	}

	

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
		widgetUpdateTask = new WidgetUpdateTask(context);
		widgetUpdateTask.execute();
	}

}
